# -*- coding: utf-8 -*-
from django.db.models import F,Q
from work.models import SubOrder
from user.models import UserRole,Role,User


def user_suborderlist(request):
    roleid_list = request.user.userrole_set.values('role_id')
    roleids = []
    for roleid in roleid_list:
        roleids.append(roleid.get('role_id'))
    objs = SubOrder.objects.filter(
        Q(approve_user=request.user) |
        Q(approve_userrole_id__in=roleids)
    )
    return objs


def has_suborder_perm(request,suborder):
    is_approve = request.user == suborder.approve_user    # 当前用户为审批用户
    userrole = UserRole.objects.filter(user=request.user,role_id=suborder.approve_userrole_id)  # 当前用户又审批的角色

    suborder_status = suborder.suborder_status == '1'   # 1为待处理
    return all([suborder_status,any([is_approve,userrole])])


def suborder_detail(request, workorder_id):
    suborder_objs = SubOrder.objects.filter(mainorder=workorder_id).order_by('sequence_number')
    suborder_list = []
    for suborder in suborder_objs:
        has_perm = has_suborder_perm(request, suborder)
        suborder_list.append({
            'id': suborder.id,
            'sequence_number': suborder.sequence_number,
            'has_perm': has_perm,
            'approve_user': suborder.approve_user.username if suborder.approve_user else '',
            'approve_user_role': suborder.approve_user_role,
            'action_status': suborder.get_action_status_display(),
        })
    return suborder_list


def handle_suborder_approve(request):
    action_status = request.data.get('action_status')
    suborder_id = request.data.get('suborder_id')
    approve_text = request.data.get('approve_text')
    suborder_obj = SubOrder.objects.get(id=suborder_id)
    if action_status == '1':  # 通过
        suborder_obj.action_status = '1'
        suborder_obj.suborder_status = '2'  # 已经处理
        handle_next_suborder_approve(suborder_obj)
    elif action_status == '2':  # 退回
        suborder_obj.action_status = '2'
        suborder_obj.suborder_status = '2'  # 已经处理
    else: # 否决
        suborder_obj.action_status = '3'
        suborder_obj.suborder_status = '2'  # 已经处理
    suborder_obj.save()


def handle_next_suborder_approve(suborder_obj):
    print( dir( suborder_obj.mainorder ) )
    sub_num = len( suborder_obj.mainorder.suborder_set.all() )
    sequence_number = suborder_obj.sequence_number

    from celery_task import tasks

    if sequence_number < sub_num:  # 有下一个审批节点
        next_sequence_number = sequence_number + 1
        next_sub_obj = SubOrder.objects.get(sequence_number=next_sequence_number, mainorder=suborder_obj.mainorder)
        next_sub_obj.suborder_status = '1'
        next_sub_obj.save()
        tasks.send_sms_code.delay(18538752511,())    # 通知审判者
    else:
        tasks.send_sms_code.delay(18538752511, ())   # 通知创建者工单已经完成